package com.spread.libpicserver;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

@RestController
public class Controller {

    @Value("${picbase}")
    private String path;

    @PostMapping("upload/picture")
    public Response uploadPicture(@RequestParam("pic") MultipartFile file) throws IOException {
        if(file == null){
            return new Response(false, "Upload picture", "File is null, check your http interface.");
        }

        if(file.isEmpty()){
            return new Response(false, "Upload picture", "File is empty.");
        }

        System.out.println("file name: " + file.getOriginalFilename());

        File f = new File(path + file.getOriginalFilename());
        if(!f.exists()){
            file.transferTo(f);
        }else{
            return new Response(false, "Upload picture", "File " + file.getOriginalFilename() + " has already existed.");
        }

        if(f.exists()){
            return new Response(true, "Upload picture", "Uploading success!");
        }else{
            return new Response(false, "Upload picture", "Internal-server error.");
        }

    }

    @GetMapping("download/picture")
    public PictureResponse downloadPicture(@RequestParam("name") String name) throws IOException {
        PictureResponse res = new PictureResponse(false, "Download Picture");
        System.out.println("path: " + path);
        File f = new File(path + name);
        if(f.exists()){
            res.setData(Files.readAllBytes(Paths.get(f.toURI())));
            res.setName(name);
            res.setMsg("Download success!");
            res.setStatus(true);
        }else{
            res.setMsg("Download fail, file " + name + " does not exist.");
        }
        return res;
    }


}
